﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;
using System.IO;

namespace UpgradeTool
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("TracyGUI.exe"))
            {
                Console.WriteLine("Please exit Tracy and press any key to start");
                Console.Read();
                Assembly assembly = Assembly.LoadFile(Path.GetFullPath("TracyGUI.exe"));
                Version ver = assembly.GetName().Version;
                if (ver.Major == 1 && ver.Minor <= 2)
                {
                    Console.WriteLine("Version 1.2 found, backing up files");
                    //Backup files
                    File.Copy(@"Data\Resources.xml", @"Data\Resources.xml.bak", true);
                    File.Copy(@"Data\FilterSets.xml", @"Data\FilterSets.xml.bak", true);

                    Console.WriteLine("Patching Resource.xml");
                    //Patch Resources.xml
                    XmlDocument doc = new XmlDocument();
                    doc.Load(@"Data\Resources.xml");
                    foreach (XmlElement node in doc.SelectNodes("/resources/resource"))
                    {
                        XmlElement sourceNode = doc.CreateElement("feed-source");
                        sourceNode.InnerText = "极影";
                        node.AppendChild(sourceNode);
                    }
                    doc.Save(@"Data\Resources.xml");

                    Console.WriteLine("Patching FilterSets.xml");
                    //Patch FilterSets.xml
                    doc = new XmlDocument();
                    doc.Load(@"Data\FilterSets.xml");
                    foreach (XmlElement node in doc.SelectNodes("/entries/entry/filter-sets/filter-set"))
                    {
                        XmlElement sourceNode = doc.CreateElement("feed-source");
                        sourceNode.InnerText = "极影";
                        node.AppendChild(sourceNode);
                    }
                    doc.Save(@"Data\FilterSets.xml");

                    //Delete old plugin
                    if (File.Exists("Plugins\\Tracy.Plugins.DownloadAdapters.dll"))
                    {
                        File.Delete("Plugins\\Tracy.Plugins.DownloadAdapters.dll");
                    }
                }
            }
            else
            {
                Console.WriteLine("TracyGUI.exe not found, please put this tool under Tracy install folder and try again.");
            }

            Console.WriteLine("Patch completed, press any key to exit");
            Console.Read();
        }
    }
}
